<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="活动名称" prop="discountName">
        <el-input
          v-model="queryParams.discountName"
          placeholder="请输入活动名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择活动类型" clearable size="small">
          <el-option
            v-for="dict in discountTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择优惠券状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用范围" prop="availableGoods">
        <el-select v-model="queryParams.availableGoods" placeholder="请选择使用范围" clearable size="small">
          <el-option
            v-for="dict in availableGoodsOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['market:discount:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['market:discount:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['market:discount:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="discountList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动名称" align="center" prop="discountName" />
      <el-table-column label="活动范围" align="center" prop="availableGoods">
        <template slot-scope="scope">
          <dict-tag :options="availableGoodsOptions" :value="scope.row.availableGoods"/>
        </template>
      </el-table-column>
      <el-table-column label="活动类型" align="center" prop="type" >
        <template slot-scope="scope">
          <dict-tag :options="discountTypeOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="订单可使用条件" align="center" prop="availableAmount" >
        <template slot-scope="scope">
          <div v-if="scope.row.unit == '0'">
            {{scope.row.availableAmount}}元
          </div>
          <div v-else>
            {{Math.floor(scope.row.availableAmount)}}件
          </div>
        </template>
      </el-table-column>
      <el-table-column label="减免/折扣/赠送" align="center" prop="deductionAmount" >
        <template slot-scope="scope">
          <span v-if="scope.row.type == '0'  ||scope.row.type == '1'">{{scope.row.deductionAmount}}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动日期" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          {{scope.row.beginTime+ '至' +scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['market:discount:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['market:discount:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.availableGoods == '1'"  command="handleEditClass" icon="el-icon-edit-outline"
                                v-hasPermi="['market:coupon:edit']">选择分类</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.availableGoods == '2'" command="handleEditGoods" icon="el-icon-edit-outline"
                                v-hasPermi="['market:coupon:edit']">编辑商品</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.type == '3'" command="handleEditGift" icon="el-icon-edit-outline"
                                v-hasPermi="['market:coupon:edit']">编辑赠品</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店铺活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择活动类型" clearable style="width: 100%;">
            <el-option
              v-for="dict in discountTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称" prop="discountName">
          <el-input v-model="form.discountName" placeholder="请输入优惠名称" />
        </el-form-item>
        <el-form-item label="订单可使用/充值金额" prop="availableAmount">
            满<el-input style="width: 50%;margin-left: 2%" v-model="form.availableAmount" placeholder="请输入订单可使用条件" />
            <el-select v-model="form.unit" placeholder="" style="width: 20%">
              <el-option
                v-for="dict in couponUnitOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
                :disabled="dict.dictValue =='1' && form.type == '4'"
              />
            </el-select>
        </el-form-item>
        <el-form-item v-if="form.type== '0' || form.type == '1' || form.type == '4'" label="减免/折扣/赠送" prop="deductionAmount">
          <el-input v-model="form.deductionAmount" placeholder="请输入减免/赠送金额或折扣率，95折用0.95表示" />
        </el-form-item>
        <el-form-item label="活动日期" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.type != '4'" label="可使用商品" prop="availableGoods">
          <el-select v-model="form.availableGoods" placeholder="请选择使用范围" style="width: 100%">
            <el-option
              v-for="dict in availableGoodsOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑商品分类对话框 -->
    <el-dialog :title="title" :visible.sync="classOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动名称" prop="couponName">
              {{form.discountName}}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择商品分类" prop="stock">
              <treeselect style="width: 100%;"
                          v-model="form.classIds"
                          :options="goodsClassList"
                          :normalizer="normalizer"
                          :show-count="true"
                          :clearable="true"
                          :flat="true"
                          :multiple="true"
                          placeholder="请选择商品分类" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog :title="title" :visible.sync="goodsOpen" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleGoodsEdit"
          >新增/编辑商品</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteGoods"
          >批量删除</el-button>
        </el-col>
      </el-row>
      <el-table  :data="goodsList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品信息" align="center" width="370" >
          <template slot-scope="scope">
            <div style="height: 100%">
              <div style="display: inline-block;float:left;width: 80px;height: 80px"  >
                <el-image :src="baseUrl+scope.row.picturePath"></el-image>
              </div>
              <div style="display: inline-block;float:left;margin-left: 15px;height: 100%;width: 250px">
                <div style="text-align: left">{{scope.row.goodsCode}}</div>
                <div style="text-align: left">{{scope.row.name}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售价" align="center" prop="referencePrice"/>
        <el-table-column label="库存" align="center" prop="stock" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteGoods(scope.row)"
              >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="goodsTotal>0"
        :total="goodsTotal"
        :page.sync="queryGoodsParams.pageNum"
        :limit.sync="queryGoodsParams.pageSize"
        @pagination="getListGoods"
      />


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑赠品对话框 -->
    <el-dialog :title="title" :visible.sync="giftOpen" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleGoodsEdit"
          >新增/编辑赠品</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteGift"
          >批量删除</el-button>
        </el-col>
      </el-row>
      <el-table  :data="goodsList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品信息" align="center" width="370" >
          <template slot-scope="scope">
            <div style="height: 100%">
              <div style="display: inline-block;float:left;width: 80px;height: 80px"  >
                <el-image :src="baseUrl+scope.row.picturePath"></el-image>
              </div>
              <div style="display: inline-block;float:left;margin-left: 15px;height: 100%;width: 250px">
                <div style="text-align: left">{{scope.row.goodsCode}}</div>
                <div style="text-align: left">{{scope.row.name}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售价" align="center" prop="referencePrice"/>
        <el-table-column label="库存" align="center" prop="stock" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteGift(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="goodsTotal>0"
        :total="goodsTotal"
        :page.sync="queryGoodsParams.pageNum"
        :limit.sync="queryGoodsParams.pageSize"
        @pagination="getListGift"
      />


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择器 -->
    <goods-selector
      ref="goodsSelector"
      :open="goodsSelector"
      :multiple="-1"
      @input="getCheckedGoods"
      @close="closeSelector"
    ></goods-selector>

  </div>
</template>

<script>
import {
  listDiscount,
  getDiscount,
  delDiscount,
  addDiscount,
  updateDiscount,
  changeDiscountStatus, getGoodsList, addGoods, delDiscountGoods, delDiscountGift, getGiftList, addGift
} from "@/api/market/discount";
import {listGoodsClass} from "@/api/goods/goodsClass";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import GoodsSelector from "@/views/goods/goods/goodsSelector";

export default {
  name: "Discount",
  components: {
    Treeselect,
    GoodsSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      baseUrl:process.env.VUE_APP_BASE_API,
      // 总条数
      total: 0,
      // 店铺活动表格数据
      discountList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      classOpen: false,
      goodsOpen: false,
      giftOpen : false,
      statusOptions: [],
      discountTypeOptions:[],
      couponUnitOptions:[],
      goodsClassList: [],
      goodsIds:[],
      goodsList : [],
      goodsTotal : 0,
      goodsSelector:false,
      // 可使用商品  0为全部商品，1为指定商品字典
      availableGoodsOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        discountName: null,
        type: null,
        status: null,
        availableGoods: null
      },
      queryGoodsParams: {
        pageNum: 1,
        pageSize: 10,
        id:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        discountName: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
          { max: 20, message: '活动名称名称长度不能超过20个字符', trigger: 'blur' }
        ],
        availableAmount: [
          { required: true, message: "订单可使用条件不能为空", trigger: "blur" },
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "金额格式不正确",trigger: "blur" }
        ],
        type: [
          { required: true, message: "活动类型不能为空", trigger: "change" }
        ],
        deductionAmount: [
          { required: true, message: "减免金额/折扣率不能为空", trigger: "blur" },
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "减免金额/折扣率格式不正确",trigger: "blur" }
        ],
        availableGoods: [
          { required: true, message: "可使用商品范围不能为空", trigger: "change" }
        ],
        dateRange:[
          { required: true, message: "活动日期不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("store_common_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("discount_type").then(response => {
      this.discountTypeOptions = response.data;
    });
    this.getDicts("coupon_unit").then(response => {
      this.couponUnitOptions = response.data;
    });
    this.getDicts("available_goods").then(response => {
      this.availableGoodsOptions = response.data;
    });
    this.getGoodsClassList();
  },
  methods: {
    /** 查询店铺活动列表 */
    getList() {
      this.loading = true;
      listDiscount(this.queryParams).then(response => {
        this.discountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询商品分类列表 */
    getGoodsClassList() {
      listGoodsClass().then(response => {
        this.goodsClassList = this.handleTree(response.data, "id");
      });
    },
    //treeSelect自定义键名
    normalizer(node) {
      return {
        id: node.id,
        label: node.className,
        children: node.children,
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.classOpen = false;
      this.goodsOpen = false;
      this.giftOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        discountName: null,
        availableAmount: null,
        unit: '0',
        type: null,
        deductionAmount: null,
        beginTime: null,
        endTime: null,
        status: "0",
        availableGoods: null,
        dateRange:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    // 多选框选中数据
    handleGoodsSelectionChange(selection) {
      this.goodsIds = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleEditClass":
          this.handleEditClass(row);
          break;
        case "handleEditGoods":
          this.handleEditGoods(row);
          break;
        case "handleEditGift":
          this.handleEditGift(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店铺活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDiscount(id).then(response => {
        this.form = response.data;
        this.form.dateRange=[this.form.beginTime,this.form.endTime]
        this.open = true;
        this.title = "修改店铺活动";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDiscount(this.form).then(response => {
              this.msgSuccess("操作成功");
              this.open = false;
              this.classOpen = false;
              this.getList();
            });
          } else {
            this.form.beginTime=this.form.dateRange[0]
            this.form.endTime=this.form.dateRange[1]
            addDiscount(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除店铺活动编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDiscount(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 修改状态 */
    handleStatusChange(row){
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.couponName + '"优惠券吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeDiscountStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleEditClass(row){
      this.reset();
      const id = row.id || this.ids
      getDiscount(id).then(response => {
        this.form = response.data;
        this.title="选择商品分类";
        this.classOpen=true;
      });
    },
    handleEditGoods(row){
      this.queryGoodsParams.id = row.id;
      this.getListGoods();
      this.title = "活动商品管理"
      this.goodsOpen = true;
    },
    getListGoods(){
      getGoodsList(this.queryGoodsParams).then(response => {
        this.goodsList = response.rows;
        this.goodsTotal = response.total;
      });
    },
    handleGoodsEdit(){
      this.goodsSelector=true;
    },
    handleDeleteGoods(row){
      const ids = row.id || this.goodsIds;
      this.$confirm('是否确认删除选中的活动商品吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delDiscountGoods(ids);
      }).then(() => {
        this.getListGoods();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleEditGift(row){
      this.queryGoodsParams.id = row.id;
      this.getListGift();
      this.title = "活动赠品管理"
      this.giftOpen = true;
    },
    getListGift(){
      getGiftList(this.queryGoodsParams).then(response => {
        this.goodsList = response.rows;
        this.goodsTotal = response.total;
      });
    },
    handleDeleteGift(row){
      const ids = row.id || this.goodsIds;
      this.$confirm('是否确认删除选中的活动赠品吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delDiscountGift(ids);
      }).then(() => {
        this.getListGift();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //选择器确定选择
    getCheckedGoods(checkedGoodsList){
      let goodsIds = [];
      checkedGoodsList.forEach(goods=>{
        goodsIds.push(goods.id)
      })

      //数据处理
      if(this.goodsOpen && goodsIds.length > 0 ){
        const form={
          id:this.queryGoodsParams.id,
          goodsIds:goodsIds
        }
        addGoods(form).then(response => {
         this.getListGoods();
        })
      }else if(this.giftOpen){
        const form={
          id:this.queryGoodsParams.id,
          goodsIds:goodsIds
        }
        addGift(form).then(response => {
          this.getListGift();
        })
      }
    },
    //关闭选择器
    closeSelector(){
      this.goodsSelector=false;
    },

  }
};
</script>
